<template>
	<div class="function-config">
		<el-button class="ml10" icon="folder-add" type="primary" @click="handleAdd">新增</el-button>
		<el-button class="ml10" icon="upload-filled" plain type="primary" @click="excelUploadModelRef.show()"> 导入 </el-button>
		<!-- <el-button class="ml10" icon="upload-filled" plain type="primary" @click="exportModel"> 导出 </el-button> -->
		<el-table :data="data" style="width: 100%" height="500">
			<el-table-column type="index" label="序号" width="80" />
			<el-table-column prop="type" label="功能类型" />
			<el-table-column prop="name" label="功能名称" />
			<el-table-column prop="description" label="描述" />
			<el-table-column prop="unit" label="单位" />
			<el-table-column prop="identifier" label="标识符" />
			<el-table-column prop="dataTypeName" label="数据类型" />
			<el-table-column prop="params" label="数据定义" show-overflow-tooltip />
			<el-table-column fixed="right" label="操作" width="200" align="center">
				<template #default="scope">
					<el-button link type="primary" @click="handleUpdate(scope.row)">修改 </el-button>
					<el-button link type="primary" @click="handleDel(scope.row)">删除 </el-button>
				</template>
			</el-table-column>
		</el-table>
		<function-detail ref="functionDetailRef" :id="id" :model="model" />
		<upload-excel
			ref="excelUploadModelRef"
			title="物模型信息导入"
			temp-url="/admin/sys-file/local/file/thingmodel.xlsx"
			temp-name="物模板.xlsx"
			:data="objData"
			url="/admin/accessThingModel/import"
			@refreshDataList="importSuccessData"
		/>
	</div>
</template>

<script lang="ts" setup>
import { propTypes } from '/@/utils/propTypes';
import { saveObjectModel } from '/@/api/basiciot/device/product';
import { useEmitt } from '/@/hooks/useEmitt';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';

import other from '/@/utils/other';

const FunctionDetail = defineAsyncComponent(() => import('./functionDetail.vue'));

const { t } = useI18n();

const { emitter } = useEmitt();

const excelUploadModelRef = ref();

const props = defineProps({
	id: propTypes.string.def(''),
	model: propTypes.object.def({}),
});
const state = reactive({
	total: 0,
	page: {
		pageSize: 10,
		pageNum: 1,
	},
	query: {},
	loading: false,
});

const objData = {
	productKey: props.id,
};

const functionDetailRef = ref();
const handleAdd = () => {
	functionDetailRef.value.openDialog();
};
const handleUpdate = (row: any) => {
	let tmpModel = JSON.parse(JSON.stringify(row));
	console.log('tmpModel', tmpModel);
	if (!tmpModel.raw.dataType) {
		tmpModel.raw.dataType = {};
	}
	tmpModel.raw.inputData = tmpModel.raw.inputData ? tmpModel.raw.inputData : [];
	tmpModel.raw.outputData = tmpModel.raw.outputData ? tmpModel.raw.outputData : [];
	let prop = tmpModel.raw;
	const props: any = {};
	if (prop.dataType.type == 'enum') {
		let enumSpecs: any[] = [];
		for (var p in prop.dataType.specs) {
			enumSpecs.push({
				name: prop.dataType.specs[p],
				value: p,
			});
		}
		props.enumItems = enumSpecs;
	} else if (prop.dataType.type == 'bool') {
		props.boolItem = {
			_true: prop.dataType.specs['0'],
			_false: prop.dataType.specs['1'],
		};
	}
	functionDetailRef.value.openDialog(toRaw(row), props);
};

// 导入成功之后刷新表格数据
const importSuccessData = () => {
	emitter.emit('updateObjectModel');
};

const submitThingModelChange = () => {
	if (props.model) {
		props.model.services = props.model.services || [];
		props.model.properties = props.model.properties || [];
		props.model.events = props.model.events || [];
	}
	saveObjectModel({
		productKey: props.id,
		model: props.model,
	}).then(() => {
		state.loading = false;
		emitter.emit('updateObjectModel');
		useMessage().success('删除成功');
	});
};

// 删除
const handleDel = (row: any) => {
	state.loading = true;
	useMessageBox()
		.confirm(t('common.delConfirmText'))
		.then(() => {
			if (row.type == 'property') {
				let index = props.model.properties.findIndex((p) => {
					return p.identifier == row.identifier;
				});
				// eslint-disable-next-line vue/no-mutating-props
				props.model.properties.splice(index, 1);
			} else if (row.type == 'service') {
				let index = props.model.services.findIndex((s) => {
					return s.identifier == row.identifier;
				});
				// eslint-disable-next-line vue/no-mutating-props
				props.model.services.splice(index, 1);
			} else if (row.type == 'event') {
				let index = props.model.events.findIndex((e) => {
					return e.identifier == row.identifier;
				});
				// eslint-disable-next-line vue/no-mutating-props
				props.model.events.splice(index, 1);
			}
			submitThingModelChange();
		});
};

const data = ref<any[]>([]);
// 获取数据
const getInfo = (model) => {
	const modelObj = model || {
		properties: [],
		events: [],
		services: [],
	};
	let modelFuncs: any[] = [];
	modelObj.properties.forEach((p) => {
		let params = JSON.stringify(p.dataType.specs || '{}');
		modelFuncs.push({
			raw: p,
			type: 'property',
			name: p.name,
			identifier: p.identifier,
			description: p.description,
			unit: p.unit,
			iconId: p.iconId,
			icon: p.icon,
			dataTypeName: p.dataType.type,
			params: params == '{}' ? '' : params,
		});
	});
	modelObj.events.forEach((e) => {
		let output = {};
		e.outputData.forEach((p) => {
			output[p.identifier] = p.name;
		});
		modelFuncs.push({
			raw: e,
			type: 'event',
			name: e.name,
			description: e.description,
			identifier: e.identifier,
			dataTypeName: '-',
			params: JSON.stringify(output),
		});
	});
	modelObj.services.forEach((s) => {
		let input: any = {};
		s.inputData.forEach((p) => {
			input[p.identifier] = p.name;
		});
		let output = {};
		s.outputData.forEach((p) => {
			output[p.identifier] = p.name;
		});
		modelFuncs.push({
			raw: s,
			type: 'service',
			name: s.name,
			description: s.description,
			identifier: s.identifier,
			dataTypeName: '-',
			params: '输入:' + JSON.stringify(input) + ',输出:' + JSON.stringify(output),
		});
	});

	console.log('modelFuncs', modelFuncs);
	data.value = modelFuncs;
};

const exportModel = () => {
	other.downBlobFile('/admin/accessThingModel/export', { productKey: props.id }, '物模型模板列表.xlsx');
};

watch(
	() => props.model,
	(newV) => {
		if (newV) getInfo(newV);
	},
	{
		deep: true,
		immediate: true,
	}
);
</script>
